package test.orm;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import web1.bean.user;
import web1.orm.mybatis1.UserDao;
import web1.orm.mybatis1.mybatisFactory;

public class testMybatis1 {
	SqlSession sqlSession;
	UserDao userDao;
	
	@Before
	public void setUp() throws Exception {
		 sqlSession = mybatisFactory.getSqlSession();
		 userDao = sqlSession.getMapper(UserDao.class);
	}

	@After
	public void tearDown() throws Exception {
	}

//	@Test
	public void selectByID() {
		int id = 2;
		user curUser = userDao.selectById(id);
		if (curUser != null) {
			System.out.println("selectById:" + curUser.getName());
		}
	}

//	@Test
	public void selectByName() {
	
		String name = "x";
		List<user> users = userDao.selectByName(name);
		if (!users.isEmpty()) {
			System.out.println("selectByName begin:");
			for (user u : users) {
				System.out.println(u.getName());
			}
			System.out.println("selectByName end:");
		}
	}

//	@Test

    public void addUser() {
        user user = new user();
        user.setName("xg");
        user.setAge(30);
        user.setSex("男");
        
     
        try {
        	
        	userDao.insert(user);
        	sqlSession.commit();
            System.out.println("新增用户ID：" + user.getId());
        } finally {
        	sqlSession.close();
        }
    }

    /**

     * 修改后要commit

     */
//	@Test

    public void updateUser() {
    
         try {
         
            user user = userDao.selectById(1);
            if (user != null) {
                user.setAge(21);
                userDao.update(user);
                sqlSession.commit();
                System.out.println("修改用户，ID=" + user.getId());
            }
        } finally {
        	sqlSession.close();
        }
    }

    /**

     * 删除后要commit.

     * 

     * @param id

     */
	@Test

    public void deleteUser() {
		int id=7;
         try {       
         	userDao.delete(id);
         	sqlSession.commit();
            System.out.println("删除用户，ID=" + id);
        } finally {
        	sqlSession.close();
        }
    }
}
